package fr.sedoo.metadata.client.ui.editablechosen;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.SelectElement;
import com.google.gwt.query.client.GQuery;
import com.google.gwt.query.client.plugins.Plugin;
import com.google.web.bindery.event.shared.EventBus;
import com.watopi.chosen.client.ChosenOptions;

public class FreeTextChosen extends GQuery {

	// A shortcut to the class
	public static final Class<FreeTextChosen> Chosen = GQuery.registerPlugin(FreeTextChosen.class, new Plugin<FreeTextChosen>() {
		public FreeTextChosen init(GQuery gq) {
			return new FreeTextChosen(gq);
		}
	});

	public static String FREE_TEXT_CHOSEN_DATA_KEY = "freeTextChosen";

	/**
	 * Indicate if the current browser is supported by the plugin or not.
	 * 
	 * @return
	 */
	public static boolean isSupported() {
		return GWT.<FreeTextChosenImpl> create(FreeTextChosenImpl.class).isSupported();
	}

	// Initialization
	public FreeTextChosen(GQuery gq) {
		super(gq);
	}

	public FreeTextChosen freeTextChosen() {
		return freeTextChosen(new ChosenOptions(), null);
	}

	public FreeTextChosen freeTextChosen(ChosenOptions options) {
		return freeTextChosen(options, null);
	}

	public FreeTextChosen freeTextChosen(final ChosenOptions options, final EventBus eventBus) {

		for (Element e : elements()) {

			if ("select".equalsIgnoreCase(e.getTagName()) && !$(e).hasClass("chzn-done")) {

				FreeTextChosenImpl impl = GWT.create(FreeTextChosenImpl.class);
				impl.init(SelectElement.as(e), options, eventBus);
				$(e).data(FREE_TEXT_CHOSEN_DATA_KEY, impl);

			}
		}
		return this;
	}

	public FreeTextChosen freeTextChosen(EventBus eventBus) {
		return freeTextChosen(null, eventBus);

	}

	public FreeTextChosen destroy() {

		for (Element e : elements()) {

			FreeTextChosenImpl impl = $(e).data(FREE_TEXT_CHOSEN_DATA_KEY, FreeTextChosenImpl.class);

			if (impl != null) {
				impl.release();
				$(e).removeData(FREE_TEXT_CHOSEN_DATA_KEY);
			}
		}
		return this;
	}

	public ChosenOptions options() {
		if (isEmpty()) {
			return null;
		}

		FreeTextChosenImpl impl = data(FREE_TEXT_CHOSEN_DATA_KEY, FreeTextChosenImpl.class);

		return impl != null ? impl.getOptions() : null;

	}

	public FreeTextChosen update() {
		for (Element e : elements()) {
			FreeTextChosenImpl impl = $(e).data(FREE_TEXT_CHOSEN_DATA_KEY, FreeTextChosenImpl.class);

			if (impl != null) {
				impl.update();
			}
		}

		return this;
	}
}
